#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:zhangcong
# Email:zc_92@sina.com


from django.shortcuts import render, redirect
from webadmin.views_dir import pub

from webadmin import models
from django.http import JsonResponse

from datetime import datetime
from webadmin.views_dir.mongo_oper import get_db_obj
from bson.objectid import ObjectId


# 标签管理
@pub.is_login
def tag_management(request):
    if "pageNum" in request.POST:
        pageNum = int(request.POST.get("pageNum"))
    else:
        pageNum = 1

    if "numPerPage" in request.POST:
        numPerPage = int(request.POST.get("numPerPage"))
    else:
        numPerPage = 20

    tags_objs_all = get_db_obj().tags.find()
    count = tags_objs_all.count()  # 用户的总数
    tags_objs = tags_objs_all.skip(pageNum * numPerPage - numPerPage).limit(numPerPage)

    # 所有用户的信息
    user_data = {}
    for i in get_db_obj().user.find({}, {"_id": 1, "username": 1}):
        user_data[i["_id"]] = i["username"]

    return render(request, 'webadmin/tag/tag_management.html', locals())


@pub.is_login
def tag_management_oper(request, oper_type, o_id):

    user_id = request.session['user_id']
    response = pub.BaseResponse()

    if request.method == "POST":
        # 添加
        if oper_type == "add":

            name = request.POST.get('name')

            if not response.statusCode and not name.strip():
                response.statusCode = 300
                response.message = "标签名称不能为空"

            if not response.statusCode:
                tags_obj = get_db_obj().tags.find_one({"name": name})
                if tags_obj:
                    response.statusCode = 300
                    response.message = "标签已存在"

            if not response.statusCode:
                get_db_obj().tags.insert({
                    "_id": str(ObjectId()),
                    "name": name,
                    "hit": 0,                       # 命中次数,表示有多少人点击了这个标签
                    "create_user_id": user_id,
                    "create_date": datetime.now()
                })
                response.statusCode = 200
                response.message = "添加成功"

        # 修改
        elif oper_type == "update":

            name = request.POST.get('name')

            if not response.statusCode and not name.strip():
                response.statusCode = 300
                response.message = "标签名称不能为空"

            if not response.statusCode:
                tags_obj = get_db_obj().tags.find_one({"name": name, "_id": {"$ne": o_id}})
                if tags_obj:
                    response.statusCode = 300
                    response.message = "标签已存在"

            if not response.statusCode:
                get_db_obj().tags.update({"_id": o_id}, {"$set": {
                    "name": name,
                }})

                response.statusCode = 200
                response.message = "修改成功"

        # 删除
        elif oper_type == "del":

            # 判断该用户下是否有文章
            article_obj = get_db_obj().articles.find_one({"tag_id": o_id})
            if article_obj:
                response.statusCode = 300
                response.message = "删除失败,该标签下存在文章,请联系管理员将文章转移后在进行该操作"
                response.callbackType = None
            else:
                get_db_obj().tags.remove({"_id": o_id})

                response.statusCode = 200
                response.message = "删除成功"
                response.callbackType = None

        return JsonResponse(response.__dict__)

    else:
        # 添加
        if oper_type == "add":
            return render(request, 'webadmin/tag/tag_management_modal_add.html', locals())

        # 修改
        elif oper_type == "update":
            tag_obj = get_db_obj().tags.find_one({"_id": o_id})

            return render(request, 'webadmin/tag/tag_management_modal_update.html', locals())
